import { reactive, onMounted, ref, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
export function useTable(
  loadDataFunc: Function,
  queryForm: object,
  dataRoot: string = "users",
  isPagination: boolean = true
) {
  const loading = ref(true);
  const tableData = ref(new Array<any>());
  const total = ref(0);
  const tableHeight = ref("0px");
  const router = useRouter();
  const route = useRoute();
  const pagination = reactive({
    page: 1,
    limit: 10,
  });

  const getTableData = async () => {
    loading.value = true;
    getTableHeight(160, 45); //获取表格的自适应高度
    try {
      const res = await loadDataFunc({ ...queryForm, ...pagination });
      if (res) {
        const obj: any = res[dataRoot];
        if (isPagination) {
          const { totalCount, items } = obj;
          tableData.value = items;
          total.value = totalCount;
        } else {
          tableData.value = obj;
        }
        loading.value = false;
      } else {
        loading.value = false;
      }
    } catch (error: any) {
      loading.value = false;
    }
  };
  const getTableHeight = (tabletop: number, tableBottom: number): void => {
    const top: number = tabletop; //el-table距离窗口顶部偏移量
    const bottom: number = tableBottom; //
    const pageHeight: number = window.innerHeight; //页面的高度
    if (document.getElementsByClassName("el-pagination").length > 0) {
      //判断页面有木有分页，来控制表格的高度自适应
      tableHeight.value = pageHeight - top - bottom + "px";
    } else {
      tableHeight.value = pageHeight - top + "px";
    }
  };
  onMounted(() => {
    getTableData();
  });
  // 搜索
  const handleSearch = () => {
    // pagination.page = 1;
    getTableData();
  };
  const refreshTableInfo = () => {
    //刷新当前路由
    const { fullPath } = route;
    nextTick(() => {
      router.replace({
        path: "/redirect" + fullPath,
      });
    });
  };
  return {
    loading,
    tableData,
    total,
    pagination,
    getTableData,
    handleSearch,
    tableHeight,
    refreshTableInfo,
  };
}
